package com.gingkor.common.ext

import com.google.gson.Gson
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible

class ParameterizedTypeImpl(private val clz: Class<*>) : ParameterizedType {
    override fun getRawType(): Type = List::class.java

    override fun getOwnerType(): Type? = null

    override fun getActualTypeArguments(): Array<Type> = arrayOf(clz)
}

/**
 * String 转 ListBean
 */
inline fun <reified T> String.toBeanList(): List<T> =
    Gson().fromJson<List<T>>(this, ParameterizedTypeImpl(T::class.java))

/**
 * String 转 Bean
 */
inline fun <reified T> String.toBean(): T = Gson().fromJson("", T::class.java)

/**
 * Bean 转 Json
 */
fun Any.toJson(): String = Gson().toJson(this)

fun Any.toMap(): Map<String, String> {
    val map = mutableMapOf<String,String>()
    this.javaClass.kotlin.memberProperties.forEach {
        it.isAccessible = true
        it.get(this)?.let{value->
            map[it.name] =value.toString()
        }

    }
    return map
}